package com.google.code.b0rx0r.ui;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class MidiNoteSelector extends JPanel {
	private JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 127, 1));
	private JToggleButton tbLearn = new JToggleButton(Messages.getString("MidiNoteSelector.learn")); //$NON-NLS-1$
	
	private int note;
	private volatile boolean learning = false;
	
	
	public MidiNoteSelector() {
		initGui();
	}

	private void initGui() {
		setLayout(new BorderLayout());
		add(spinner, BorderLayout.CENTER);
		add(tbLearn, BorderLayout.EAST);
		
		spinner.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent arg0) {
				int newNote = (Integer)spinner.getValue();
				
				if (newNote != note) {
					int oldNote = note;
					note = newNote;
					firePropertyChange("note", oldNote, note); //$NON-NLS-1$
				}
			}
		});
		
		tbLearn.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				if (tbLearn.isSelected()) {
					learning = true;
					
					//TODO: register listener??
				} else {
					learning = false;
					//TODO: unregister listener??
				}
			}
		});
	}

	public boolean learnNote(int note) {
		if (learning) {
			learning = false;
			tbLearn.setSelected(false);
			
			if (this.note != note) {
				int oldNote = this.note;
			  this.note = note; 
			  spinner.setValue(note);
			  firePropertyChange("note", oldNote, note); //$NON-NLS-1$
			}
			
			return true;
		}
		return false;
	}

	public void setNote(int note) {
		this.note = note;
		spinner.setValue(note);
	}

}
